import { Actions } from 'react-native-router-flux';
import { Tabs, Toast, Stepper } from '@ant-design/react-native';

import axios from 'axios'
import store from '../store/store'
import { logout } from '../router/module'

import { apiPath, removeData } from '../util/utils.js'


axios.defaults.validateStatus = (status) => {
    return status < 1000
}

const api = {
    get(url, data) {
        return axios.get(url, { params: { ...data } })
    },
    post(url, data) {
        return axios({
            method: 'post',
            url,
            data: data || {},
        })
    },
}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    let authorization = store.getState().auth.authorization
    if (authorization) {
        config.headers.accessToken = authorization
        config.headers.Authorization = authorization
    }
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'

    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    console.log(response)
    // 对响应数据做点什么
    if (response.status == 401 || response.data.code == 401) {
        if (response.config.url.indexOf('login') < 0) {
            logout()
        }
    }

    if (response.status == 405) {
        Toast.fail(response.data.message || response.data.errMsg, 1, null, false)
    }

    if (response.status >= 500 && response.status < 600) {
        response.error = response.data
        Toast.fail(response.data.message || response.data.errMsg, 1, null, false)
    }

    if (response.headers.authorization) {
        response.data.data.authorization = response.headers.authorization
    }
    return response;
}, function (error) {
    console.log(error)
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default api
